package servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.alibaba.fastjson.JSONObject;

import bean.UserBean;
import dao.UserDao;

/**
 * Servlet implementation class RegisterServlet
 */
@WebServlet("/register")
public class RegisterServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public RegisterServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		
		String user_name = request.getParameter("user_name");
		String user_realname = request.getParameter("user_realname");
		String user_password = request.getParameter("user_password");
		String user_phone = request.getParameter("user_phone");
		
		boolean flag = UserDao.check_phone(user_phone);
		System.out.println(flag);
		if (flag) {

			request.setAttribute("msg", "此手机号已被注册！如需解绑请联系管理员！");
			request.getRequestDispatcher("/register.jsp").forward(request, response);
		}else {
			UserDao.register(user_name, user_realname, user_password, user_phone);
			UserBean user = new UserBean(user_name, user_realname, user_password, user_phone);
			
			// 将用户信息加入session，保存登录状态
			HttpSession ss = request.getSession();
			ss.setAttribute("now_user", user);

			request.setAttribute("user_phone", user_phone);
			request.setAttribute("user_password", user_password);
			request.getRequestDispatcher("/login.jsp").forward(request, response);
		}
		
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
